<script setup>
import { ref, onMounted } from 'vue'
import { message, Modal } from 'ant-design-vue'
import request, { getServerUrl } from '@/utils/request'
import { useUserStore } from '@/stores/user'
import { useRouter } from 'vue-router'

const router = useRouter()
const userStore = useUserStore()
const records = ref([])
const loading = ref(false)
const serverUrl = getServerUrl()

// 格式化日期时间
const formatDateTime = (dateTimeStr) => {
  try {
    const date = new Date(dateTimeStr)
    return date.toLocaleString()
  } catch (e) {
    return dateTimeStr || '未知时间'
  }
}

// 获取完整图片URL
const getFullImageUrl = (imagePath) => {
  if (!imagePath) return '';
  
  // 如果已经是完整URL，直接返回
  if (imagePath.startsWith('http') || imagePath.startsWith('data:')) {
    return imagePath;
  }
  
  // 否则拼接服务器地址
  return serverUrl + imagePath;
}

// 获取记录列表
const fetchRecords = async () => {
  loading.value = true
  try {
    const user = userStore.user
    
    if (!user || !user.id) {
      message.error('请先登录')
      router.push('/login')
      return
    }
    
    const res = await request.post('/record/getList', {
      user_id: user.id
    })
    
    if (res.data.code === 200) {
      // 转换API返回的数据格式
      records.value = res.data.data.map(record => ({
        id: record.id,
        type: record.category,
        confidence: '95%', // 假设信息，实际应从识别时保存
        time: formatDateTime(record.created_time),
        imageUrl: getFullImageUrl(record.image),
        recycle_method: record.recycle_method,
        name: record.name
      }))
      
      if (records.value.length === 0) {
        message.info('暂无识别记录')
      }
    } else {
      message.error(res.data.message || '获取记录失败')
    }
  } catch (error) {
    console.error('获取记录失败:', error)
    message.error('获取记录失败: ' + (error.message || '未知错误'))
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  fetchRecords()
})

// 删除记录
const deleteRecord = async (id) => {
  try {
    // 显示确认对话框
    Modal.confirm({
      title: '确认删除',
      content: '确认要删除这条记录吗？删除后无法恢复。',
      okText: '删除',
      okType: 'danger',
      cancelText: '取消',
      async onOk() {
        loading.value = true
        
        const user = userStore.user
        if (!user || !user.id) {
          message.error('请先登录')
          return
        }
        
        // 调用后端API删除记录
        const res = await request.post('/record/delete', {
          record_id: id,
          user_id: user.id
        })
        
        if (res.data.code === 200) {
          // 从前端列表中移除该记录
          records.value = records.value.filter(record => record.id !== id)
          message.success(res.data.message || '删除成功')
        } else {
          message.error(res.data.message || '删除失败')
        }
        
        loading.value = false
      }
    })
  } catch (error) {
    console.error('删除失败:', error)
    message.error('删除失败: ' + (error.message || '未知错误'))
    loading.value = false
  }
}

// 表格列定义
const columns = [
  {
    title: '图片',
    dataIndex: 'imageUrl',
    key: 'imageUrl',
    width: 120,
  },
  {
    title: '垃圾名称',
    dataIndex: 'name',
    key: 'name',
  },
  {
    title: '垃圾类型',
    dataIndex: 'type',
    key: 'type',
  },
  {
    title: '处理建议',
    dataIndex: 'recycle_method',
    key: 'recycle_method',
    ellipsis: true,
  },
  {
    title: '识别时间',
    dataIndex: 'time',
    key: 'time',
  },
  {
    title: '操作',
    key: 'action',
  },
]
</script>

<template>
  <div class="records-container">
    <h2>识别记录</h2>
    
    <a-spin :spinning="loading">
      <a-table
        :columns="columns" 
        :data-source="records" 
        :rowKey="record => record.id"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'imageUrl'">
            <img 
              v-if="record.imageUrl" 
              :src="record.imageUrl" 
              alt="垃圾图片" 
              style="width: 60px; height: 60px; object-fit: cover" 
            />
            <span v-else>无图片</span>
          </template>
          
          <template v-else-if="column.key === 'type'">
            <a-tag :color="record.type === '可回收物' ? 'blue' : 
                          record.type === '有害垃圾' ? 'red' : 
                          record.type === '厨余垃圾' ? 'green' : 'orange'">
              {{ record.type }}
            </a-tag>
          </template>
          
          <template v-else-if="column.key === 'action'">
            <a-button type="link" danger @click="deleteRecord(record.id)">删除</a-button>
          </template>
        </template>
        
        <template #emptyText>
          <a-empty description="暂无识别记录" />
        </template>
      </a-table>
    </a-spin>
  </div>
</template>

<style scoped>
.records-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}
h2 {
  text-align: center;
  margin-bottom: 30px;
}
</style> 